package com.slipper.codeless.resolve.support;

import com.slipper.constants.Constants;
import com.slipper.util.DatabaseUtil;
import com.slipper.util.Tool;

public class PostgresqlSqlBuilder extends CommonSqlBuilder {

    @Override
    public String getSymbol() {
        return DatabaseUtil.getSymbol(Constants.Database.POSTGRESQL);
    }

    @Override
    public String getQueryRecursiveSql(String tableName, String pidName, String idName, String param) {
        String tempName = "tmp_" + Tool.getUUID();
        return "with recursive " + tempName + " as (" +
                "    select " + wrapSymbol(idName) + ", " + wrapSymbol(pidName) +
                "    from " + wrapSymbol(tableName) +
                "    where " + wrapSymbol(idName) + "=#{" + param + "}" +
                "    union all" +
                "    select t." + wrapSymbol(idName) + ", t." + wrapSymbol(pidName) +
                "    from " + wrapSymbol(tableName) + " t" +
                "        inner join " + tempName + " p on t." + wrapSymbol(pidName) + " = p." + wrapSymbol(idName) +
                ") select " + wrapSymbol(idName) + " from " + tempName;
    }

    @Override
    public String getQueryOrgLevelSql(String param) {
        return "with recursive tmp_organization_tree as (" +
                "    select id, parent_id from sys_organization where id = #{" + param + "}" +
                "    union all" +
                "    select o.id, o.parent_id from sys_organization o inner join tmp_organization_tree p on o.parent_id = p.id" +
                ") select id from tmp_organization_tree";
    }
}
